import logging
from typing import Dict, Optional
from app.models.user import user_model
from app.services.shopify_api_service import shopify_api_service

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

class UserService:
    """
    用户服务
    处理用户注册、信息获取和更新等业务逻辑
    """
    
    def register_user(self, shopify_domain: str, access_token: Optional[str] = None) -> Dict:
        """
        注册用户
        
        Args:
            shopify_domain: Shopify店铺域名
            access_token: Shopify访问令牌（可选）
            
        Returns:
            Dict: 注册结果
        """
        try:
            # 清理域名格式
            cleaned_domain = self._clean_shopify_domain(shopify_domain)
            
            # 检查用户是否已存在
            if user_model.user_exists(cleaned_domain):
                user_info = user_model.get_user_by_domain(cleaned_domain)
                return {
                    "success": True,
                    "message": "用户已存在",
                    "user_id": user_info.get('user_id'),
                    "shopify_domain": cleaned_domain,
                    "user_info": user_info
                }
            
            # 如果提供了访问令牌，尝试获取店铺信息
            shop_info = None
            if access_token:
                shop_info = shopify_api_service.get_shop_info(cleaned_domain, access_token)
                if shop_info:
                    # 只保留需要的字段
                    shop_info = {
                        'shop_name': shop_info.get('shop_name'),
                        'shop_owner': shop_info.get('shop_owner'),
                        'email': shop_info.get('email'),
                        'country': shop_info.get('country'),
                        'currency': shop_info.get('currency'),
                        'plan_name': shop_info.get('plan_name')
                    }
            
            # 创建用户
            user_id = user_model.create_user(cleaned_domain, shop_info)
            
            # 获取创建后的用户信息
            user_info = user_model.get_user_by_domain(cleaned_domain)
            
            return {
                "success": True,
                "message": "用户注册成功",
                "user_id": user_id,
                "shopify_domain": cleaned_domain,
                "user_info": user_info
            }
            
        except Exception as e:
            logging.error(f"注册用户失败: {shopify_domain}, 错误: {str(e)}")
            return {
                "success": False,
                "message": f"注册失败: {str(e)}",
                "shopify_domain": shopify_domain
            }
    
    def update_user_by_domain(self, shopify_domain: str, access_token: str) -> Dict:
        """
        根据域名更新用户信息
        
        Args:
            shopify_domain: Shopify店铺域名
            access_token: Shopify访问令牌
            
        Returns:
            Dict: 更新结果
        """
        try:
            # 清理域名格式
            cleaned_domain = self._clean_shopify_domain(shopify_domain)
            
            # 检查用户是否存在
            if not user_model.user_exists(cleaned_domain):
                return {
                    "success": False,
                    "message": "用户不存在，请先注册",
                    "shop_domain": cleaned_domain
                }
            
            # 从Shopify获取最新店铺信息
            shop_info = shopify_api_service.get_shop_info(cleaned_domain, access_token)
            if not shop_info:
                return {
                    "success": False,
                    "message": "无法获取店铺信息，请检查访问令牌是否有效",
                    "shop_domain": cleaned_domain
                }
            
            # 准备更新数据
            update_data = {
                'shop_name': shop_info.get('shop_name'),
                'shop_owner': shop_info.get('shop_owner'),
                'email': shop_info.get('email'),
                'country': shop_info.get('country'),
                'currency': shop_info.get('currency'),
                'plan_name': shop_info.get('plan_name')
            }
            
            # 更新用户信息
            success = user_model.update_user(cleaned_domain, update_data)
            
            if success:
                # 获取更新后的用户信息
                user_info = user_model.get_user_by_domain(cleaned_domain)
                return {
                    "success": True,
                    "message": "用户信息更新成功",
                    "shop_domain": cleaned_domain,
                    "user_info": user_info
                }
            else:
                return {
                    "success": False,
                    "message": "用户信息更新失败",
                    "shop_domain": cleaned_domain
                }
                
        except Exception as e:
            logging.error(f"更新用户信息失败: {shopify_domain}, 错误: {str(e)}")
            return {
                "success": False,
                "message": f"更新失败: {str(e)}",
                "shop_domain": shopify_domain
            }
    
    def get_user_info(self, shopify_domain: str) -> Dict:
        """
        获取用户信息
        
        Args:
            shopify_domain: Shopify店铺域名
            
        Returns:
            Dict: 用户信息结果
        """
        try:
            # 清理域名格式
            cleaned_domain = self._clean_shopify_domain(shopify_domain)
            
            # 获取用户信息
            user_info = user_model.get_user_by_domain(cleaned_domain)
            
            if user_info:
                return {
                    "success": True,
                    "message": "获取用户信息成功",
                    "shopify_domain": cleaned_domain,
                    "user_info": user_info
                }
            else:
                return {
                    "success": False,
                    "message": "用户不存在",
                    "shopify_domain": cleaned_domain
                }
                
        except Exception as e:
            logging.error(f"获取用户信息失败: {shopify_domain}, 错误: {str(e)}")
            return {
                "success": False,
                "message": f"获取失败: {str(e)}",
                "shopify_domain": shopify_domain
            }
    
    def process_user(self, shopify_domain: str, access_token: str, device_info: Optional[Dict] = None) -> Dict:
        """
        统一处理用户注册和信息同步
        
        根据用户提供的shopify_domain和access_token，检查用户是否存在。
        如果存在则更新信息，不存在则创建新用户。
        始终获取完整的店铺信息并存储。
        
        Args:
            shopify_domain: Shopify店铺域名
            access_token: Shopify访问令牌
            device_info: 设备信息（可选）
            
        Returns:
            Dict: 操作结果
        """
        try:
            # 清理域名格式
            cleaned_domain = self._clean_shopify_domain(shopify_domain)
            
            # 验证访问令牌是否有效
            if not shopify_api_service.verify_access_token(cleaned_domain, access_token):
                return {
                    "success": False,
                    "message": "访问令牌无效，请检查输入",
                    "shopify_domain": cleaned_domain
                }
            
            # 获取完整的店铺信息
            complete_shop_info = shopify_api_service.get_complete_shop_info(cleaned_domain, access_token)
            if not complete_shop_info:
                return {
                    "success": False,
                    "message": "无法获取店铺完整信息",
                    "shopify_domain": cleaned_domain
                }
            
            # 准备用于用户表的数据（只保留用户表需要的字段）
            user_shop_info = {
                'shop_name': complete_shop_info.get('shop_name'),
                'shop_owner': complete_shop_info.get('shop_owner'),
                'email': complete_shop_info.get('email'),
                'country': complete_shop_info.get('country'),
                'currency': complete_shop_info.get('currency'),
                'plan_name': complete_shop_info.get('plan_name')
            }
            
            # 检查用户是否存在
            if user_model.user_exists(cleaned_domain):
                # 用户存在，更新信息
                success = user_model.update_user(cleaned_domain, user_shop_info)
                if success:
                    user_info = user_model.get_user_by_domain(cleaned_domain)
                    return {
                        "success": True,
                        "message": "用户信息更新成功",
                        "shopify_domain": cleaned_domain,
                        "user_info": user_info,
                        "complete_shop_info": complete_shop_info
                    }
                else:
                    return {
                        "success": False,
                        "message": "用户信息更新失败",
                        "shopify_domain": cleaned_domain
                    }
            else:
                # 用户不存在，创建新用户
                user_id = user_model.create_user(cleaned_domain, user_shop_info)
                user_info = user_model.get_user_by_domain(cleaned_domain)
                
                # 如果提供了设备信息，可以在这里记录（需要扩展用户表或创建新表）
                if device_info:
                    logging.info(f"记录设备信息: {cleaned_domain}, 设备: {device_info}")
                
                return {
                    "success": True,
                    "message": "用户注册成功",
                    "user_id": user_id,
                    "shopify_domain": cleaned_domain,
                    "user_info": user_info,
                    "complete_shop_info": complete_shop_info
                }
                
        except Exception as e:
            logging.error(f"处理用户失败: {shopify_domain}, 错误: {str(e)}")
            return {
                "success": False,
                "message": f"操作失败: {str(e)}",
                "shopify_domain": shopify_domain
            }
    
    def register_and_sync_user(self, shopify_domain: str, access_token: str) -> Dict:
        """
        注册用户并同步店铺信息（保留向后兼容）
        
        Args:
            shopify_domain: Shopify店铺域名
            access_token: Shopify访问令牌
            
        Returns:
            Dict: 操作结果
        """
        # 调用统一处理方法
        result = self.process_user(shopify_domain, access_token)
        
        # 为了向后兼容，移除complete_shop_info字段
        if "complete_shop_info" in result:
            del result["complete_shop_info"]
            
        return result
    
    def _clean_shopify_domain(self, shopify_domain: str) -> str:
        """
        清理Shopify域名格式
        
        Args:
            shopify_domain: 原始域名
            
        Returns:
            str: 清理后的域名
        """
        if not shopify_domain:
            return ""
        
        # 移除协议前缀
        cleaned = shopify_domain.strip()
        if cleaned.startswith(('http://', 'https://')):
            cleaned = cleaned.split('://', 1)[1]
        
        # 移除尾部斜杠
        if cleaned.endswith('/'):
            cleaned = cleaned[:-1]
        
        # 确保包含myshopify.com后缀
        if '.myshopify.com' not in cleaned and '.' not in cleaned:
            cleaned = f"{cleaned}.myshopify.com"
        
        return cleaned


# 创建服务实例
user_service = UserService()